package com.whj.controller;

import com.whj.domain.dto.LoginUserDTO;
import com.whj.domain.entity.LoginUser;
import com.whj.domain.entity.Menu;
import com.whj.domain.enums.AppHttpCodeEnum;
import com.whj.domain.response.ResponseResult;
import com.whj.domain.vo.*;
import com.whj.exception.SystemException;
import com.whj.service.MenuService;
import com.whj.service.RoleService;
import com.whj.service.SystemLoginService;
import com.whj.utils.BeanCopyUtils;
import com.whj.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Auther: wanghaijun
 * @Date: 2023/5/30 - 05 - 30 - 9:56 
 * @Description: com.whj.controller
 */

@RestController
public class SystemLoginController {

    @Autowired
    private SystemLoginService systemLoginServiceImpl;

    /**
     * 后台用户登录
     *
     * @param loginUserDTO
     * @return
     */
    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody LoginUserDTO loginUserDTO) {
        if (!StringUtils.hasText(loginUserDTO.getUserName())) {
            //提示 必须要传用户名
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return systemLoginServiceImpl.login(loginUserDTO);
    }

    @PostMapping("/user/logout")
    public ResponseResult logout(){
        return systemLoginServiceImpl.logout();
    }

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    /**
     * 根据用户登录的id获取对应的权限
     *
     * @return
     */
    @GetMapping("getInfo")
    public ResponseResult<AdminUserInfoVo> getInfo() {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 获取用户id
        Long userId = loginUser.getUser().getId();
        // 根据id查询权限
        List<String> permissions = menuService.selectPermsByUserId(userId);
        // 根据id查询角色信息
        List<String> roles = roleService.selectRoleByUserId(userId);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        AdminUserInfoVo vo = new AdminUserInfoVo();
        vo.setPermissions(permissions);
        vo.setRoles(roles);
        vo.setUser(userInfoVo);
        return ResponseResult.okResult(vo);

    }


    /**
     * @return
     */
    @GetMapping("/getRouters")
    public ResponseResult<AdminUserRoutersVo> getRouters() {
        Long userId = SecurityUtils.getUserId();
        // 查询menu 结果返回tree的形式
        List<Menu> menuList = menuService.selectRouterMenuTreeByUserId(userId);
        //封装返回数据
        return ResponseResult.okResult(new RoutersVo(menuList));
    }
}
